<?php

class JhrechargeAction extends Action{
	
	private $to_rate;
	private $openid;
	private $phone_key;
	private $flow_key;
	private $game_key;
	private $phone_status;
	private $flow_status;
	private $game_status;
	public function _initialize(){
		
		$this->to_rate = model("Xdata")->getConfig("to_rate","scoreSetting","admin_Score");
		$this->openid = model("Xdata")->getConfig("to_rate","rechargeSetting","admin_Score");
		$this->phone_key = model("Xdata")->getConfig("phone_key","rechargeSetting","admin_Score");
		$this->flow_key = model("Xdata")->getConfig("flow_key","rechargeSetting","admin_Score");
		$this->game_key = model("Xdata")->getConfig("game_key","rechargeSetting","admin_Score");
		$this->phone_status = model("Xdata")->getConfig("phone_status","rechargeSetting","admin_Score");
		$this->flow_status = model("Xdata")->getConfig("flow_status","rechargeSetting","admin_Score");
		$this->game_status = model("Xdata")->getConfig("game_status","rechargeSetting","admin_Score");
		
	}
	
	public function checkStatus($type){
		
		if($type == 'phone'){
			if($this->phone_status){
				$value = ["code" =>"enable"];
				header("Content-Type: text/json");
				die(et($value));
			}else{
				$value = ["code" =>"disable"];
				header("Content-Type: text/json");
				die(et($value));
			}
		}elseif($type == 'flow'){
			if($this->flow_status){
				$value = ["code" =>"enable"];
				header("Content-Type: text/json");
				die(et($value));
			}else{
				$value = ["code" =>"disable"];
				header("Content-Type: text/json");
				die(et($value));
			}
		}elseif($type == 'game'){
			if($this->game_status){
				$value = ["code" =>"enable"];
				header("Content-Type: text/json");
				die(et($value));
			}else{
				$value = ["code" =>"disable"];
				header("Content-Type: text/json");
				die(et($value));
			}
		}
		
		$value = ["code" =>"false"];
		header("Content-Type: text/json");
		die(et($value));
	}
	
	public function checkRecharge(){//【检查充值服务开启状态】
		$type = dt($_REQUEST['type']);
		$this->checkStatus($type);
	}
	
	public function creditCompare($uid,$credit){//【判断积分是否足够】
		$credit_user = M('Credit_user');
		$get_info = $credit_user->where("uid = $uid")->find();
		if($credit > $get_info['score']){
			return false;
		}
		return true;
		
	}
	
	public function creditUpdate($uid,$new_credit){//【更新用户积分】
		$credit_user = M('Credit_user');
		$get_info = $credit_user->where("uid = $uid")->find();
		$credit_user->uid = $uid;
		$credit_user->score = $new_credit;
		if($credit_user->save()){
			return true;
		}
		return false;
		
	}
	
	public function getCredit($uid){//【获取用户积分】
		$credit_user = M('Credit_user');
		$get_info = $credit_user->where("uid = $uid")->find();
		return $get_info['score'];
	
	}
	
	public function addRechargeData($uid,$credit,$type,$orderid,$flow='',$sporder_id,$phone){//【添加充值记录】
		$recharge = M('Recharge');
		$time = time();
		//id uid orderid type credit money ctime
		$recharge->uid = $uid;
		$recharge->credit = $credit;
		$recharge->type = $type;
		$recharge->orderid = $orderid;
		if($type == '话费'){
			$recharge->money = $credit/$this->to_rate;
			$recharge->phone = $phone;
		}
		if($type == '流量'){
			$recharge->flow = $flow;
			$recharge->phone = $phone;
		}
		if($type == '游戏'){
			$recharge->money = $credit/$this->to_rate;
		}
		$recharge->ctime = $time;
		$id = $recharge->add();
		return $recharge->where("id = $id")->find();
	}
	
	public function checkFpassword($uid,$fpassword){//【验证交易密码】
		$user = M('User');
		$login = $user->where("uid = $uid")->find();
		$md5f = md5(md5($fpassword).$login['login_salt']);
		
		if($md5f == $login['fpassword']){
			return true;
			
		}else{
			return false;
		}
	
	}
	
	public function getNeed(){//【获取所需积分】
		
		$money = dt($_REQUEST['money']);
		
		$credit = round($money)*$this->to_rate;
		
		if($credit){
			$value = ["code" =>"success",'credit'=>$credit];
			header("Content-Type: text/json");
			die(et($value));
		}else{
			$value = ["code" =>"false"];
			header("Content-Type: text/json");
			die(et($value));
		}
	}
	
	function juhecurl($url,$params=false,$ispost=0){
   	 	$httpInfo = array();
   	 	$ch = curl_init();
 
    	curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    	curl_setopt( $ch, CURLOPT_USERAGENT , 'JuheData' );
   	 	curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
    	curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
    	curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    	if( $ispost )
    	{
       	 curl_setopt( $ch , CURLOPT_POST , true );
        	curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
        	curl_setopt( $ch , CURLOPT_URL , $url );
    	}
    	else
    	{
        	if($params){
            	curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
        	}else{
            	curl_setopt( $ch , CURLOPT_URL , $url);
        	}
    	}
    	$response = curl_exec( $ch );
    	if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        	return false;
    	}
    	$httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
    	$httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
    	curl_close( $ch );
    	return $response;
	}

public function checkPhone($phone,$pervalue){//【检查手机是否可以充值】
		$url = "http://v.juhe.cn/huafei/telcheck";
		$params = array(
     	 "phone" => "",//手机号码
     	 "pervalue" => "",//充值面额，可选：10,20,30,50,100,200,300,500
     	 "key" => $this->phone_key,//应用APPKEY(应用详细页查询)
			);
		$params['phone'] = $phone;
		$params['pervalue'] = $pervalue;
		
		$paramstring = http_build_query($params);
		
		$content = $this->juhecurl($url,$paramstring);
		
		$result = json_decode($content,true);
		if($result){
    		if($result['error_code']=='0'){
        		return true;
    		}else{
       			return false;
  	  		}
		}else{
    		return false;
		}
	
	}
	
	
	public function phoneRecharge(){//【手机充值接口】
		if(!$this->phone_status){
			$value = ["code" =>"disable"];
			header("Content-Type: text/json");
			die(et($value));
		}
		$phone = dt($_REQUEST['phone']);
		$uid = dt($_REQUEST['uid']);
		$fpassword = dt($_REQUEST['fpassword']);
		if(!$this->checkFpassword($uid, $fpassword)){//交易密码错误 
			$value = ["code" =>"fpasswordfalse"];
			header("Content-Type: text/json");
			die(et($value));
		}
		
		$orderid = rand(10000,99999).time();
		$pervalue =  dt($_REQUEST['pervalue']);
		if(!in_array($pervalue, array(10,20,30,50,100,200,300,500))){//充值额不支持
			$value = ["code" =>"pervaluefalse"];
			header("Content-Type: text/json");
			die(et($value));
		
		}
		$credit = $pervalue*$this->to_rate;
		
		if(!$this->checkPhone($phone, $pervalue)){
			$value = ["code" =>"phonefalse"];
			header("Content-Type: text/json");
			die(et($value));
		}
		
		$url = "http://v.juhe.cn/huafei/recharge";
		$params = array(
      					"phone" => "",//手机号码
      					"pervalue" => "",//充值面额，可选:10,20,30,50,100,200,300,500
      					"orderid" => "",//自定义订单号，8-32位字母数字组合
      					"key" => $this->phone_key,//应用APPKEY(应用详细页查询)
     					 "sign" => "",//校验值，md5(&lt;b&gt;OpenID&lt;/b&gt;+key+phone+pervalue+orderid)，OpenID在个人中心查询，结果转为32小写
						);
		//定义请求参数
		$params['phone'] = $phone;
		$params['pervalue'] = $pervalue;
		$params['orderid'] = $orderid;
		$params['sign'] = md5($this->openid.$params['key'].$params['phone'].$params['pervalue'].$params['orderid']);
		//格式化参数
		$paramstring = http_build_query($params);
		$content = $this->juhecurl($url,$paramstring);
		//判断积分是否够用
		if(!$this->creditCompare($uid, $credit)){//积分不足
			$value = ["code" =>"creditfalse"];
			header("Content-Type: text/json");
			die(et($value));
		}
		//更新用户积分
		$old_credit = $this->getCredit($uid);
		$new_credit = $old_credit-$credit;
		if(!$this->creditUpdate($uid, $new_credit)){
			$value = ["code" =>"false"];
			header("Content-Type: text/json");
			die(et($value));
		
		}
		//发送json请求
		$result = json_decode($content,true);
		if($result){//请求成功
				$type = '话费';
    			$return = $this->addRechargeData($uid, $credit, $type, $orderid,'',$result['sporder_id'],$phone);
       		 	$value = ["code" =>"success",'data'=>$return];
				header("Content-Type: text/json");
				die(et($value));
       		 	
    		if($result['error_code']=='0'){//充值成功
    			//充值记录写入数据库
				$type = '话费';
    			$return = $this->addRechargeData($uid, $credit, $type, $orderid,'',$result['sporder_id'],$phone);
       		 	$value = ["code" =>"success",'data'=>$return];
				header("Content-Type: text/json");
				die(et($value));
    		}else{//充值失败
    			$this->creditUpdate($uid, $old_credit);
    			$value = ["code" =>"false"];
    			header("Content-Type: text/json");
				die(et($value));
    			
    		}
		}else{//请求失败
			$this->creditUpdate($uid, $old_credit);
    		$value = ["code" =>"false"];
			header("Content-Type: text/json");
			die(et($value));
		}
	}
	
	public function checkFlow(){//【检查手机支持的流量套餐】
		$url = "http://v.juhe.cn/flow/telcheck";
		$params = array(
      	"phone" => "",//要查询的手机号码
      	"key" => $this->flow_key,//应用APPKEY(应用详细页查询)
		);
		$params['phone'] = dt($_REQUEST['phone']);
		$paramstring = http_build_query($params);
		
		$content = $this->juhecurl($url,$paramstring);
		//dump($paramstring);exit;
		$result = json_decode($content,true);
		if($result){
   	 		if($result['error_code']=='0'){
        		$value = ["code" =>"success",'data'=>$result['result']];
        		header("Content-Type: text/json");
				die(et($value));
    		}else{
        		$value = ["code" =>"false"];
				header("Content-Type: text/json");
				die(et($value));
    		}
		}else{
    		$value = ["code" =>"false"];
			header("Content-Type: text/json");
			die(et($value));
		}
	
	}
	public function rechargeFlow(){//【提交流量充值】
		if(!$this->flow_status){
			$value = ["code" =>"disable"];
			header("Content-Type: text/json");
			die(et($value));
		}
		$url = "http://v.juhe.cn/flow/recharge";
		$orderid = rand(10000,99999).time();
		$flow = dt($_REQUEST['flow']);//流量值
		$uid = dt($_REQUEST['uid']);
		$fpassword = dt($_REQUEST['fpassword']);
		$money = dt($_REQUEST['money']);
		if(empty($flow) || empty($uid) || empty($fpassword) || empty($money)){//检查参数是否为空
			$value = ["code" =>"empty"];
			header("Content-Type: text/json");
			die(et($value));
		
		}
		
		$credit = round($money)*$this->to_rate;
		if(!$this->checkFpassword($uid, $fpassword)){//交易密码错误 
			$value = ["code" =>"fpasswordfalse"];
			header("Content-Type: text/json");
			die(et($value));
		}
		$params = array(
      		"phone" => "",//需要充值流量的手机号码
      		"pid" => "",//流量套餐ID
     		"orderid" => "",//自定义订单号，8-32字母数字组合
      		"key" => $this->flow_key,//应用APPKEY(应用详细页查询)
      		"sign" => "",//校验值，md5(&lt;b&gt;OpenID&lt;/b&gt;+key+phone+pid+orderid)，结果转为小写
			);
		//定义参数
		$params['phone'] = $phone =dt($_REQUEST['phone']);
		$params['pid'] = $pid = dt($_REQUEST['pid']);
		$params['orderid'] = $orderid;
		$params['sign'] = md5($this->openid.$params['key'].$params['phone'].$params['pid'].$params['orderid']);
		$paramstring = http_build_query($params);
		$content = $this->juhecurl($url,$paramstring);
		//判断积分是否够用
		if(!$this->creditCompare($uid, $credit)){//积分不足
			$value = ["code" =>"creditfalse"];
			header("Content-Type: text/json");
			die(et($value));
		}
		//更新用户积分
		$old_credit = $this->getCredit($uid);
		$new_credit = $old_credit-$credit;
		if(!$this->creditUpdate($uid, $new_credit)){
			$value = ["code" =>"false"];
			header("Content-Type: text/json");
			die(et($value));
		
		}
		//发送json请求
		$result = json_decode($content,true);
		if($result){
				$type = '流量';
    			$return = $this->addRechargeData($uid, $credit, $type, $orderid,$flow,$result['sporder_id'],$phone);
       		 	$value = ["code" =>"success",'data'=>$return];
				header("Content-Type: text/json");
				die(et($value));
			
    		if($result['error_code']=='0'){
    			$type = '流量';
    			$return = $this->addRechargeData($uid, $credit, $type, $orderid,$flow,$result['sporder_id'],$phone);
       		 	$value = ["code" =>"success",'data'=>$return];
				header("Content-Type: text/json");
				die(et($value));
    			
    		}else{
    			$this->creditUpdate($uid, $old_credit);
    			$value = ["code" =>"false"];
    			header("Content-Type: text/json");
				die(et($value));
        	
    		}
		}else{//请求失败
			$this->creditUpdate($uid, $old_credit);
    		$value = ["code" =>"false"];
			header("Content-Type: text/json");
			die(et($value));
		}
	
	}
	
	public function getGameList(){//【获取所有游戏列表】
		
		$url = "http://op.juhe.cn/ofpay/game/cardlist";
		$params = array(
      		"key" => $this->game_key,//应用APPKEY(应用详细页查询)
			);
		$paramstring = http_build_query($params);
		
		$content = $this->juhecurl($url,$paramstring);
		$result = json_decode($content,true);
		
		if($result){//请求成功
    		if($result['error_code']=='0'){//获取成功
    			$data = array();
    			foreach ($result['result'] as $key=>$res){
    				if($res['cardid'] != '22130'){
    					$data[$key]['cardid'] = $res['cardid'];
    					$data[$key]['cardname'] = $res['cardname'];
    				}
    			}
    			$data = array_values($data);
    			//dump($data);exit;
       		 	$value = ["code" =>"success",'data'=>$data];
       		 	
				header("Content-Type: text/json");
				die(et($value));
    		}else{//获取失败
        		$value = ["code" =>"false"];
    			header("Content-Type: text/json");
				die(et($value));
    		}
		}else{//请求失败
    		$value = ["code" =>"false"];
			header("Content-Type: text/json");
			die(et($value));
		}
		
	}
	
	public function getGamePervalue(){//根据游戏列表的cardid获取所包含详细游戏列表
			$url = "http://op.juhe.cn/ofpay/game/cardinfo";
			$params = array(
      			"cardid" => "",//对应接口1的cardid
      			"key" => $this->game_key,//应用APPKEY(应用详细页查询)
				);
			//定义参数
			$params['cardid'] = dt($_REQUEST['cardid']);
			//$params['cardid'] = $_REQUEST['cardid'];
			$paramstring = http_build_query($params);
			$content = $this->juhecurl($url,$paramstring);
			$result = json_decode($content,true);
			if($result){//请求成功
    			if($result['error_code']=='0'){//获取成功
    				
	    			$data = array();
	    			foreach ($result['result'] as $key=>$res){
	    					$data[$key]['cardid'] = $res['cardid'];
	    					$data[$key]['cardname'] = $res['cardname'];
							$data[$key]['subclassid'] = $res['subclassid'];
	    			}
    				
    				
       		 		$value = ["code" =>"success",'data'=>$data];
       		 		header("Content-Type: text/json");
					die(et($value));
    			}else{//获取失败，该游戏暂时不能充值
        			$value = ["code" =>"false"];
        			header("Content-Type: text/json");
					die(et($value));
    			}
			}else{//请求失败
    			$value = ["code" =>"false"];
    			header("Content-Type: text/json");
				die(et($value));
			}
	
	}
	
	public function getGamePrice(){//根据详细游戏列表的cardid获取所包含游戏的及其可充值面额和可购买数量
			$url = "http://op.juhe.cn/ofpay/game/cardprice";
			$params = array(
      			"cardid" => "",//对应接口1的cardid
      			"key" => $this->game_key,//应用APPKEY(应用详细页查询)
				);
			//定义参数
			$params['cardid'] = dt($_REQUEST['cardid']);
			//$params['cardid'] = $_REQUEST['cardid'];
			$paramstring = http_build_query($params);
			$content = $this->juhecurl($url,$paramstring);
			$result = json_decode($content,true);
			if($result){//请求成功
    			if($result['error_code']=='0'){//获取成功
       		 		$value = ["code" =>"success",'data'=>$result['result']];
       		 		
					header("Content-Type: text/json");
					die(et($value));
    			}else{//获取失败，该游戏暂时不能充值
        			$value = ["code" =>"false"];
        			
    				header("Content-Type: text/json");
					die(et($value));
    			}
			}else{//请求失败
    			$value = ["code" =>"false"];
    			
				header("Content-Type: text/json");
				die(et($value));
			}
	
	}
	
	public function getGameAreaserver(){//根据游戏详细列表对应的cardid获取游戏所在区域和服务器
		$url = "http://op.juhe.cn/ofpay/game/areaserver";
		$params = array(
      		"cardid" => "",//对应接口3的cardid
      		"key" => $this->game_key,//应用APPKEY(应用详细页查询)
			);
		//定义参数
		$params['cardid'] = dt($_REQUEST['cardid']);
		//$params['cardid'] = $_REQUEST['cardid'];
		$paramstring = http_build_query($params);
		$content = $this->juhecurl($url,$paramstring);
		$result = json_decode($content,true);
			if($result){//请求成功
    			if($result['error_code']=='0'){//获取成功
    				foreach ($result['result'] as $key=>$res){
	    					unset($result['result'][$key]['AREAFLAG']);
	    					unset($result['result'][$key]['SERVERFLAG']);
	    			}
	    			if(empty($result['result'])){
	    				$result['result'] = array();
	    			}
    				$value = ["code" =>"success",'data'=>$result['result']];
    				
       		 		header("Content-Type: text/json");
					die(et($value));
    			}else{//获取失败
        			$value = ["code" =>"false"];
        			
    				header("Content-Type: text/json");
					die(et($value));
    			}
			}else{//请求失败
    			$value = ["code" =>"false"];
    			
				header("Content-Type: text/json");
				die(et($value));
			}
	}
	
	public function rechargeGame(){//【游戏充值】
		if(!$this->game_status){
			$value = ["code" =>"disable"];
			header("Content-Type: text/json");
			die(et($value));
		}
		$orderid = rand(10000,99999).time();
		//$flow = dt($_REQUEST['flow']);//流量值
		$uid = dt($_REQUEST['uid']);
		$fpassword = dt($_REQUEST['fpassword']);
		
		$money = dt($_REQUEST['money']);
		$cardid = dt($_REQUEST['cardid']);
		$cardnum = dt($_REQUEST['cardnum']);
		$game_userid = dt($_REQUEST['game_userid']);
		$game_area = dt($_REQUEST['game_area']);
		$game_srv = dt($_REQUEST['game_srv']);
		if(empty($uid) || empty($fpassword) || empty($money) || empty($cardid) || empty($cardnum) || empty($game_userid)){//检查参数是否为空
			$value = ["code" =>"empty"];
			header("Content-Type: text/json");
			die(et($value));
		
		}
		
		$credit = round($money)*$this->to_rate*$cardnum;
		if(!$this->checkFpassword($uid, $fpassword)){//交易密码错误 
			$value = ["code" =>"fpasswordfalse"];
			header("Content-Type: text/json");
			die(et($value));
		}
		$url = "http://op.juhe.cn/ofpay/game/order";
		$params = array(
      		"cardid" => "",//商品编码，对应接口3的cardid
      		"cardnum" => "",//购买数量
      		"orderid" => "",//订单号，8-32位数字字母组合
      		"game_userid" => "",//游戏玩家账号(game_userid=xxx@162.com$xxx001 xxx@162.com是通行证xxx001是玩家账号)
      		"game_area" => "",//游戏所在区域，没有则不填，具体参照接口4返回，URLEncode UTF8
      		"game_srv" => "",//游戏所在服务器，没有则不填，具体参照接口4返回，URLEncode UTF8
      		"key" => $this->game_key,//应用APPKEY(应用详细页查询)
      		"sign" => "",//校验值，md5(&lt;b&gt;OpenID&lt;/b&gt;+key+cardid+cardnum+orderid+game_userid+game_area+game_srv)
		);
		//定义参数
		$params['cardid'] = $cardid;
		$params['cardnum'] = $cardnum;
		$params['orderid'] = $orderid;
		$params['game_userid'] = $game_userid;
		$params['game_area'] = urlencode($game_area);
		$params['game_srv'] = urlencode($game_srv);
		$params['sign'] = md5($this->openid.$params['key'].$cardid.$cardnum.$orderid.$game_userid.urlencode($game_area).urlencode($game_srv));
		//$params['cardid'] = $_REQUEST['cardid'];
		$paramstring = http_build_query($params);
		$content = $this->juhecurl($url,$paramstring);
		//判断积分是否够用
		if(!$this->creditCompare($uid, $credit)){//积分不足
			$value = ["code" =>"creditfalse"];
			header("Content-Type: text/json");
			die(et($value));
		}
		//更新用户积分
		$old_credit = $this->getCredit($uid);
		$new_credit = $old_credit-$credit;
		if(!$this->creditUpdate($uid, $new_credit)){
			$value = ["code" =>"false"];
			header("Content-Type: text/json");
			die(et($value));
		
		}
		//发送json请求
		$result = json_decode($content,true);
			if($result){//请求成功
					$type = '游戏';
    				$return = $this->addRechargeData($uid, $credit, $type, $orderid,'',$result['sporder_id']);
       		 		$value = ["code" =>"success",'data'=>$result['result']];
       		 		header("Content-Type: text/json");
					die(et($value));
				
    			if($result['error_code']=='0'){//获取成功
    				$type = '游戏';
    				$return = $this->addRechargeData($uid, $credit, $type, $orderid,'',$result['sporder_id']);
       		 		$value = ["code" =>"success",'data'=>$result['result']];
       		 		header("Content-Type: text/json");
					die(et($value));
    			}else{//获取失败
    				$this->creditUpdate($uid, $old_credit);
        			$value = ["code" =>"false"];
        			header("Content-Type: text/json");
					die(et($value));
    			}
			}else{//请求失败
				$this->creditUpdate($uid, $old_credit);
    			$value = ["code" =>"false"];
				header("Content-Type: text/json");
				die(et($value));
			}
	}
	
	
	public function getOrder(){
		$uid = dt($_REQUEST['uid']);
		$_REQUEST['type'] && $map['type'] = dt($_REQUEST['type']);
		$_REQUEST['id'] && $map['id'] = dt($_REQUEST['id']);
		
		$pagecount=isset($_REQUEST['pagecount'])?dt($_REQUEST['pagecount']):"10";//每页显示数量
		$pagenum=$pagecount*((isset($_REQUEST['pagenum'])?dt($_REQUEST['pagenum']):"1")-1);//当前页数
		
		$recharge = M('Recharge');
		$map['uid'] = $uid;
		$data = $recharge->where($map)->limit("$pagenum,$pagecount")->order("ctime desc")->select();
		if($data){
			$value = ["code" =>"success",'data'=>$data];
       		header("Content-Type: text/json");
			die(et($value));
		}else{
			if(M("User")->where("uid = $uid")->find()){
				$value = ["code" =>"success",'data'=>array()];
       			header("Content-Type: text/json");
				die(et($value));
			}
			
			$value = ["code" =>"false"];
			header("Content-Type: text/json");
			die(et($value));
		}
	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

}